import { AxiosPromise, AxiosRequestConfig, AxiosResponse } from "../types";
import { buildRUL } from "../helpers/url";
import xhr from "./xhr";
import { transformRequest, transformResponse } from "../helpers/data";
import { processHeaders } from "../helpers/headers";
export default function dispatchRequest(
  config: AxiosRequestConfig
): AxiosPromise {
  processConfig(config); //初始化配置
  return xhr(config).then((res) => transformResponseData(res));
}

function processConfig(config: AxiosRequestConfig) {
  config.url = transformURL(config);
  config.headers = transformHeadersData(config); //注意顺序
  config.data = transformRequestData(config);
}

function transformURL(config: AxiosRequestConfig): string {
  const { url, params } = config;
  return buildRUL(url, params);
}

function transformRequestData(config: AxiosRequestConfig): any {
  return transformRequest(config.data);
}

function transformHeadersData(config: AxiosRequestConfig): any {
  const { headers = {}, data } = config;
  return processHeaders(headers, data);
}

function transformResponseData(res: AxiosResponse): any {
  res.data = transformResponse(res.data);
  return res;
}
